<template>
  <div class="detail-container">
    <div v-if="loading" class="loading-container">
      <el-icon class="is-loading"><Loading /></el-icon>
      <p>加载中...</p>
    </div>

    <div v-else-if="item" class="content">
      <div class="header">
        <div class="header-actions">
          <div class="edit-actions">
            <el-button v-if="!isEditing" type="success" :icon="Edit" @click="startEdit">
              编辑
            </el-button>
            <template v-else>
              <el-button type="primary" :icon="Check" @click="save" :loading="saving">
                保存
              </el-button>
              <el-button :icon="Close" @click="cancelEdit">
                取消
              </el-button>
            </template>
          </div>
        </div>
        
        <div class="title-section">
          <div class="title-with-badge">
            <h1 class="title" v-if="!isEditing">
              <el-tag type="danger" size="large" effect="plain" class="content-type-badge">
                <el-icon><Flag /></el-icon>
                时政积累
              </el-tag>
              {{ item.title }}
            </h1>
            <el-input v-else v-model="editForm.title" placeholder="请输入标题" class="title-input" size="large" />
          </div>
          <el-input 
            v-if="isEditing"
            v-model="editForm.category"
            placeholder="请输入分类（可选）"
            class="category-input"
            style="margin-bottom: 20px;"
          />
          <div class="meta">
            <span class="meta-item">
              <el-icon><Calendar /></el-icon>
              创建时间：{{ item.createTime }}
            </span>
            <span class="meta-item" v-if="item.category">
              <el-icon><Folder /></el-icon>
              分类：{{ item.category }}
            </span>
            <span class="meta-item" v-if="item.source">
              <el-icon><Document /></el-icon>
              来源：{{ item.source }}
            </span>
          </div>
        </div>
      </div>

      <div class="body">
        <div class="editor-wrapper" v-if="!isEditing">
          <Editor v-model="item.content" :defaultConfig="viewEditorConfig" mode="default" style="min-height: 400px;" />
        </div>
        <div class="editor-wrapper" v-else>
          <Toolbar :editor="editorRef" :defaultConfig="toolbarConfig" mode="default" />
          <Editor v-model="editForm.content" :defaultConfig="editEditorConfig" mode="default" style="height: 500px; overflow-y: auto;" @onCreated="handleCreated" />
        </div>
      </div>
    </div>

    <div v-else class="error-container">
      <el-icon class="error-icon"><WarningFilled /></el-icon>
      <p>{{ errorMessage || '内容不存在或已被删除' }}</p>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, reactive, onBeforeUnmount, shallowRef } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Calendar, Document, Loading, WarningFilled, Edit, Check, Close, Folder, Flag } from '@element-plus/icons-vue';
import { Editor, Toolbar } from '@wangeditor/editor-for-vue';
import '@wangeditor/editor/dist/css/style.css';
import { getPoliticsAccumulationById, updatePoliticsAccumulation } from '@/api/politicsAccumulation';
import { getEditorConfig, getToolbarConfig, createEditorCallback } from '@/utils/editorUtils';
import type { IDomEditor } from '@wangeditor/editor';

const route = useRoute();
const router = useRouter();
const loading = ref(true);
const item = ref<any>(null);
const errorMessage = ref('');
const isEditing = ref(false);
const saving = ref(false);

const editorRef = shallowRef<IDomEditor>();
const mode = 'default';
const toolbarConfig = getToolbarConfig();
const handleCreated = createEditorCallback(editorRef);

const editForm = reactive({ title: '', content: '', category: '' });
const viewEditorConfig = { readOnly: true, scroll: false };
const editEditorConfig = getEditorConfig('请输入内容...', '时政积累');

const fetchDetail = async () => {
  try {
    loading.value = true;
    const id = route.query.id;
    if (!id) {
      errorMessage.value = '缺少ID参数';
      return;
    }
    
    // 使用 requestIdleCallback 优化性能
    const fetchData = async () => {
      const response: any = await getPoliticsAccumulationById(Number(id));
      if (response.code === 200) {
        item.value = response.data;
      } else {
        errorMessage.value = response.message || '获取详情失败';
        ElMessage.error(errorMessage.value);
      }
    };

    if (window.requestIdleCallback) {
      window.requestIdleCallback(() => fetchData(), { timeout: 1000 });
    } else {
      setTimeout(() => fetchData(), 0);
    }
  } catch (error: any) {
    console.error('获取时政积累详情失败:', error);
    errorMessage.value = error.message || '网络错误，请稍后重试';
    ElMessage.error(errorMessage.value);
  } finally {
    setTimeout(() => { loading.value = false; }, 100);
  }
};

const goBack = () => {
  if (isEditing.value) {
    ElMessageBox.confirm('当前正在编辑，确定要离开吗？未保存的内容将会丢失。', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }).then(() => {
      if (editorRef.value) editorRef.value.destroy();
      router.push('/');
    }).catch(() => {});
  } else {
    if (editorRef.value) editorRef.value.destroy();
    router.push('/');
  }
};

const startEdit = () => {
  editForm.title = item.value.title;
  editForm.content = item.value.content;
  editForm.category = item.value.category || '';
  isEditing.value = true;
};

const cancelEdit = () => {
  ElMessageBox.confirm('确定要取消编辑吗？未保存的内容将会丢失。', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    isEditing.value = false;
    editForm.title = '';
    editForm.content = '';
    editForm.category = '';
  }).catch(() => {});
};

const save = async () => {
  if (!editForm.title || !editForm.title.trim()) {
    ElMessage.warning('请输入标题');
    return;
  }
  if (!editForm.content || !editForm.content.trim()) {
    ElMessage.warning('请输入内容');
    return;
  }
  try {
    saving.value = true;
    const response: any = await updatePoliticsAccumulation({
      ...item.value,
      title: editForm.title.trim(),
      content: editForm.content,
      category: editForm.category?.trim() || ''
    });
    if (response.code === 200) {
      ElMessage.success('保存成功');
      item.value.title = editForm.title.trim();
      item.value.content = editForm.content;
      item.value.category = editForm.category?.trim() || '';
      isEditing.value = false;
    } else {
      ElMessage.error(response.message || '保存失败');
    }
  } catch (error: any) {
    console.error('保存失败:', error);
    ElMessage.error(error.message || '保存失败，请稍后重试');
  } finally {
    saving.value = false;
  }
};

onBeforeUnmount(() => {
  if (editorRef.value) {
    editorRef.value.destroy();
  }
});

onMounted(() => {
  requestAnimationFrame(() => fetchDetail());
});
</script>

<style scoped>
.detail-container { min-height: 100vh; background: #f5f7fa; padding: 20px; }
.loading-container, .error-container { display: flex; flex-direction: column; align-items: center; justify-content: center; min-height: 60vh; color: #909399; }
.loading-container .el-icon { font-size: 48px; margin-bottom: 20px; }
.error-container .error-icon { font-size: 64px; color: #f56c6c; margin-bottom: 20px; }
.error-container p { font-size: 16px; margin-bottom: 20px; }
.content { max-width: 1200px; margin: 0 auto; background: #fff; border-radius: 8px; box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08); }
.header { padding: 30px; border-bottom: 1px solid #e4e7ed; }
.header-actions { display: flex; justify-content: flex-end; align-items: center; margin-bottom: 20px; }
.edit-actions { display: flex; gap: 10px; }
.title-section { }

.title-with-badge {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.title-with-badge .title {
  display: flex;
  align-items: center;
  gap: 12px;
  flex-wrap: wrap;
}

.content-type-badge {
  display: inline-flex;
  align-items: center;
  gap: 6px;
  font-size: 14px;
  font-weight: 600;
  padding: 8px 16px;
  border-radius: 20px;
  width: fit-content;
  flex-shrink: 0;
}

.content-type-badge .el-icon {
  font-size: 16px;
}
.title { font-size: 32px; font-weight: 600; color: #2c3e50; font-family: '仿宋', FangSong, STFangsong, serif; margin: 0 0 20px 0; line-height: 1.4; }
.title-input { margin-bottom: 20px; }
.title-input :deep(.el-input__wrapper) { font-size: 32px; font-weight: 600; font-family: '仿宋', FangSong, STFangsong, serif; padding: 10px 15px; }
.title-input :deep(.el-input__inner) { font-size: 32px; font-weight: 600; color: #2c3e50; font-family: '仿宋', FangSong, STFangsong, serif; }
.meta { display: flex; gap: 30px; flex-wrap: wrap; }
.meta-item { display: flex; align-items: center; gap: 6px; color: #909399; font-size: 14px; }
.meta-item .el-icon { font-size: 16px; }
.body { padding: 30px; }
.editor-wrapper { min-height: 400px; font-family: '仿宋', FangSong, STFangsong, serif; font-size: 16px; line-height: 1.8; }
.editor-wrapper :deep(.w-e-text-container) { background: transparent !important; }
.editor-wrapper :deep(.w-e-scroll) { background: transparent !important; }
.editor-wrapper :deep(.w-e-text-placeholder) { display: none !important; }
.editor-wrapper :deep(.w-e-text-container .w-e-scroll) { overflow-y: auto !important; }
.editor-wrapper :deep(.w-e-text-container[contenteditable="false"]) { min-height: auto !important; height: auto !important; }
.editor-wrapper :deep(.w-e-text-container[contenteditable="false"] .w-e-scroll) { min-height: auto !important; height: auto !important; overflow: visible !important; }
@media (max-width: 768px) {
  .detail-container { padding: 10px; }
  .header { padding: 20px; }
  .header-actions { flex-direction: column; align-items: stretch; gap: 15px; }
  .edit-actions { justify-content: flex-end; }
  .title { font-size: 24px; }
  .title-input :deep(.el-input__wrapper), .title-input :deep(.el-input__inner) { font-size: 24px; }
  .meta { flex-direction: column; gap: 10px; }
  .body { padding: 20px; }
}
</style>
